# ui/qt6_admin_summary.py
# -*- coding: utf-8 -*-
"""
管理员汇总窗口 - 跨用户统计报表 + 数据导出（无图表依赖版本）
"""
import sys, os, csv, datetime, glob
from pathlib import Path
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QTableView, QVBoxLayout, QWidget,
    QPushButton, QComboBox, QLabel, QHBoxLayout, QFileDialog, 
    QMessageBox, QTabWidget, QDateEdit, QProgressBar, QTextEdit
)
from PyQt6.QtCore import Qt, QSortFilterProxyModel, QDate
from PyQt6.QtGui import QStandardItemModel, QStandardItem
from openpyxl.styles import Font, Alignment
from utils.logger import log
from PyQt6.QtWidgets import QHeaderView 

class AdminSummaryWindow(QMainWindow):
    def __init__(self, data_dir):
        super().__init__()
        self.data_dir = Path(data_dir)
        self.logs_dir = self.data_dir / "logs"
        self.setWindowTitle("👑 管理员汇总 - 跨用户统计")
        self.resize(1200, 700)

        # 设置窗口属性
        self.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False)
        self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)

        self.init_ui()
        self.load_data()

    def init_ui(self):
        """初始化UI"""
        central = QWidget()
        self.setCentralWidget(central)
        layout = QVBoxLayout(central)
        
        # 顶部控制栏
        top_layout = QHBoxLayout()
        
        # 日期范围选择
        top_layout.addWidget(QLabel("开始日期:"))
        self.start_date_edit = QDateEdit()
        self.start_date_edit.setDate(QDate.currentDate().addDays(-6))  # 默认往前 7 天
        self.start_date_edit.setCalendarPopup(True)
        self.start_date_edit.dateChanged.connect(self.on_date_changed)
        top_layout.addWidget(self.start_date_edit)

        top_layout.addWidget(QLabel("结束日期:"))
        self.end_date_edit = QDateEdit()
        self.end_date_edit.setDate(QDate.currentDate())
        self.end_date_edit.setCalendarPopup(True)
        self.end_date_edit.dateChanged.connect(self.on_date_changed)
        top_layout.addWidget(self.end_date_edit)
        
        top_layout.addStretch()
        
        # 刷新按钮
        self.refresh_btn = QPushButton("🔄 刷新")
        self.refresh_btn.clicked.connect(self.refresh_data)
        top_layout.addWidget(self.refresh_btn)
        
        # 导出按钮
        self.export_btn = QPushButton("📊 导出Excel报表")
        self.export_btn.clicked.connect(self.export_comprehensive_report)
        top_layout.addWidget(self.export_btn)
        
        layout.addLayout(top_layout)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        layout.addWidget(self.progress_bar)
        
        # 标签页
        self.tabs = QTabWidget()
        layout.addWidget(self.tabs)
        
        # 创建各个标签页
        self.create_summary_tab()
        self.create_detailed_tab()

        # ★★★ 添加表格样式美化
        self.apply_table_styles()
    def apply_table_styles(self):
        """应用表格样式"""
        table_style = """
            QTableView {
                background-color: white;
                alternate-background-color: #f8f8f8;
                gridline-color: #d0d0d0;
                color: black;  /* 强制设置文字颜色为黑色 */
            }
            QTableView::item {
                padding: 5px;
                border: none;
                color: black;  /* 单元格文字颜色 */
            }
            QHeaderView::section {
                background-color: #4CAF50;
                color: white;
                padding: 8px;
                font-weight: bold;
            }
        """
        
        self.user_table.setStyleSheet(table_style)
        self.detail_table.setStyleSheet(table_style)
        
        # 设置交替行颜色
        self.user_table.setAlternatingRowColors(True)
        self.detail_table.setAlternatingRowColors(True)
        
        # 设置选择行为
        self.user_table.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
        self.detail_table.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)
        
        # 设置选择模式
        self.user_table.setSelectionMode(QTableView.SelectionMode.SingleSelection)
        self.detail_table.setSelectionMode(QTableView.SelectionMode.SingleSelection)
        
        # 设置表格不可编辑
        self.user_table.setEditTriggers(QTableView.EditTrigger.NoEditTriggers)
        self.detail_table.setEditTriggers(QTableView.EditTrigger.NoEditTriggers)

# 在 create_summary_tab 方法中修改
    def create_summary_tab(self):
        """创建汇总标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        layout.setContentsMargins(10, 10, 10, 10)  # 设置整体边距
        
        # 汇总统计信息
        self.summary_label = QLabel("正在加载数据...")
        self.summary_label.setStyleSheet("font-size: 14px; font-weight: bold; padding: 10px;")
        layout.addWidget(self.summary_label)
        
        # 用户统计表格 - 直接添加，使用拉伸因子
        self.user_table = QTableView()
        layout.addWidget(self.user_table)
        
        self.tabs.addTab(tab, "📈 汇总统计")

    # 在 create_detailed_tab 方法中修改
    def create_detailed_tab(self):
        """创建详细数据标签页"""
        tab = QWidget()
        layout = QVBoxLayout(tab)
        layout.setContentsMargins(10, 10, 10, 10)  # 设置整体边距
        
        # 详细数据表格 - 直接添加，使用拉伸因子
        self.detail_table = QTableView()
        layout.addWidget(self.detail_table)
        
        self.tabs.addTab(tab, "📋 详细数据")

    def load_data(self):
        """加载选中日期范围内的所有数据"""
        try:
            start_date = self.start_date_edit.date().toPyDate()
            end_date   = self.end_date_edit.date().toPyDate()

            self.progress_bar.setVisible(True)
            self.progress_bar.setValue(0)

            # 1. 先列出范围内所有日期
            day_count = (end_date - start_date).days + 1
            all_days  = [start_date + datetime.timedelta(days=i) for i in range(day_count)]

            # 2. 把所有 CSV 文件路径收集起来
            csv_files = []
            for day in all_days:
                pattern = f"{day.strftime('%Y-%m-%d')}_*.csv"
                csv_files.extend(self.logs_dir.glob(pattern))

            if not csv_files:
                QMessageBox.information(self, "无数据", "选中日期范围内没有找到任何用户数据")
                self.progress_bar.setVisible(False)
                return

            # 3. 开始读数据
            all_data = []
            user_stats = {}
            self.progress_bar.setMaximum(len(csv_files))

            for i, csv_file in enumerate(csv_files):
                user_id = csv_file.stem.split('_', 1)[1]   # 去掉前面的日期
                user_data = self.load_user_data(csv_file, user_id)
                all_data.extend(user_data)
                user_stats[user_id] = self.calculate_user_stats(user_data, user_id)
                self.progress_bar.setValue(i + 1)
                QApplication.processEvents()

            self.progress_bar.setVisible(False)

            # 4. 保存并刷新界面
            self.all_data = all_data
            self.user_stats = user_stats
            self.update_summary_tab(user_stats)
            self.update_detailed_tab(all_data)

        except Exception as e:
            self.progress_bar.setVisible(False)
            log(f'[ERR] 加载管理员汇总数据失败: {e}')
            QMessageBox.critical(self, "错误", f"加载数据失败:\n{e}")

    def load_user_data(self, csv_file, user_id):
        """加载单个用户的数据"""
        data = []
        try:
            with open(csv_file, 'r', encoding='utf-8-sig', newline='') as f:
                reader = csv.DictReader(f)
                for row in reader:
                    row['用户ID'] = user_id
                    data.append(row)
        except Exception as e:
            log(f'[ERR] 读取用户 {user_id} 数据失败: {e}')
        return data

    def calculate_user_stats(self, user_data, user_id):
        """计算用户统计信息"""
        stats = {
            'user_id': user_id,
            'total_records': len(user_data),
            'total_work_seconds': 0,
            'total_workload': 0,
            'state_distribution': {},
            'project_distribution': {}
        }
        
        for record in user_data:
            # 计算总工作时长
            try:
                duration = int(record.get('时长(秒)', 0))
                stats['total_work_seconds'] += duration
            except:
                pass
            
            # 计算总工作量
            try:
                workload = float(record.get('工作量1', 0))
                stats['total_workload'] += workload
            except:
                pass
            
            # 状态分布
            state = record.get('状态', '未知')
            stats['state_distribution'][state] = stats['state_distribution'].get(state, 0) + 1
            
            # 项目分布
            project = record.get('项目名称', '未指定')
            if project:
                stats['project_distribution'][project] = stats['project_distribution'].get(project, 0) + 1
        
        return stats

    def update_summary_tab(self, user_stats):
        """按 日期+用户ID+项目+作业类型+状态 汇总 总时长+工作量"""
        from collections import defaultdict

        # key:(日期,用户ID,项目,作业类型,状态)  value:[总秒数,总工作量]
        summary_map = defaultdict(lambda: [0, 0])

        for record in self.all_data:
            # 构造 key
            date_val = (record.get('\ufeff日期', '') or record.get('日期', '')).replace('-', '/')
            user_id  = record.get('用户ID', '')
            project  = record.get('项目名称', '')
            job_type = record.get('作业类型', '')
            state    = record.get('状态', '')          # ← 新增

            # 累加时长
            try:
                secs = int(record.get('时长(秒)', 0))
            except:
                secs = 0
            # 累加工作量
            try:
                workload = float(record.get('工作量1', 0))
            except:
                workload = 0

            summary_map[(date_val, user_id, project, job_type, state)][0] += secs
            summary_map[(date_val, user_id, project, job_type, state)][1] += workload

        # 建模型
        headers = ['日期', '用户ID', '状态', '项目名称', '作业类型', '总时长', '工作量']
        model = QStandardItemModel(len(summary_map), len(headers))
        model.setHorizontalHeaderLabels(headers)

        for row, (key, (total_secs, total_work)) in enumerate(summary_map.items()):
            date_val, user_id, project, job_type, state = key
            model.setItem(row, 0, QStandardItem(date_val))
            model.setItem(row, 1, QStandardItem(user_id))
            model.setItem(row, 2, QStandardItem(state))           
            model.setItem(row, 3, QStandardItem(project))
            model.setItem(row, 4, QStandardItem(job_type))
            model.setItem(row, 5, QStandardItem(self.format_duration(total_secs)))
            model.setItem(row, 6, QStandardItem(str(int(total_work))))
            for col in range(7):
                item = model.item(row, col)
                if item:
                    item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
        self.user_table.setModel(model)
        header = self.user_table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)

        self.summary_label.setText(f"📊 汇总统计（共 {len(summary_map)} 组）")

# 在 update_user_table 方法中修改
    def update_user_table(self, user_stats):
        """更新用户统计表格"""
        headers = ['用户ID', '记录数', '总时长', '总工作量', '主要状态', '主要项目']
        model = QStandardItemModel(len(user_stats), len(headers))
        model.setHorizontalHeaderLabels(headers)
        
        for row, (user_id, stats) in enumerate(user_stats.items()):
            # 用户ID - 居中对齐
            item = QStandardItem(user_id)
            item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            model.setItem(row, 0, item)
            
            # 记录数 - 居中对齐
            item = QStandardItem(str(stats['total_records']))
            item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            model.setItem(row, 1, item)
            
            # 总时长 - 居中对齐
            item = QStandardItem(self.format_duration(stats['total_work_seconds']))
            item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            model.setItem(row, 2, item)
            
            # 总工作量 - 居中对齐
            item = QStandardItem(f"{stats['total_workload']:.0f}")
            item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            model.setItem(row, 3, item)
            
            # 主要状态 - 居中对齐
            main_state = max(stats['state_distribution'].items(), key=lambda x: x[1], default=('无', 0))[0]
            item = QStandardItem(main_state)
            item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            model.setItem(row, 4, item)
            
            # 主要项目 - 居中对齐
            main_project = max(stats['project_distribution'].items(), key=lambda x: x[1], default=('无', 0))[0]
            item = QStandardItem(main_project)
            item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
            model.setItem(row, 5, item)
        
        self.user_table.setModel(model)
        
        # ★★★ 设置表格水平拉伸 - 平均拉伸所有列
        header = self.user_table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        
        # ★★★ 设置表头居中对齐
        header.setDefaultAlignment(Qt.AlignmentFlag.AlignCenter)

    def update_detailed_tab(self, all_data):
        """更新详细数据标签页"""
        if not all_data:
            model = QStandardItemModel(0, 13)  # ★★★ 改为13列
            headers = ['日期', '用户ID', '角色', '状态', '开始时间', '结束时间', '时长', '项目', '任务ID', '工作量1', '工作量2', '工作量3', '备注']
            model.setHorizontalHeaderLabels(headers)
            self.detail_table.setModel(model)
            return
        
        headers = ['日期', '用户ID', '角色', '状态', '开始时间', '结束时间', '时长', '项目', '任务ID', '工作量1', '工作量2', '工作量3', '备注']
        model = QStandardItemModel(len(all_data), len(headers))
        model.setHorizontalHeaderLabels(headers)
        
        for row, record in enumerate(all_data):
            # 所有数据都居中对齐
            columns_data = [
                (record.get('\ufeff日期', '') or record.get('日期', '')).replace('-', '/'),
                record.get('用户ID', ''),
                record.get('角色', ''),
                record.get('状态', ''),
                record.get('开始', ''),
                record.get('结束', ''),
                record.get('时长(秒)', ''),
                record.get('项目名称', ''),
                record.get('任务ID', ''),
                record.get('工作量1', ''),
                record.get('工作量2', ''),  # ★★★ 新增工作量2
                record.get('工作量3', ''),  # ★★★ 新增工作量3
                record.get('备注', '')      # ★★★ 新增备注
            ]
            
            for col, value in enumerate(columns_data):
                item = QStandardItem(str(value))
                item.setTextAlignment(Qt.AlignmentFlag.AlignCenter)
                model.setItem(row, col, item)
        
        # 设置排序代理
        proxy = QSortFilterProxyModel()
        proxy.setSourceModel(model)
        self.detail_table.setModel(proxy)
        
        # ★★★ 设置表格列宽 - 混合模式
        header = self.detail_table.horizontalHeader()
        
        # ★★★ 设置表格水平拉伸 - 平均拉伸所有列
        header = self.detail_table.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
        
        # ★★★ 设置表头居中对齐
        header.setDefaultAlignment(Qt.AlignmentFlag.AlignCenter)

    def export_comprehensive_report(self):
        """导出综合Excel报表"""
        try:
            start_str = self.start_date_edit.date().toString("yyyyMMdd")
            end_str   = self.end_date_edit.date().toString("yyyyMMdd")
            default_name = f"管理员汇总_{start_str}_{end_str}.xlsx"
            path, _ = QFileDialog.getSaveFileName(self, "保存Excel报表", default_name, "Excel Files (*.xlsx)")
            if not path:
                return
            
            self.progress_bar.setVisible(True)
            self.progress_bar.setValue(0)
            
            # 创建Excel工作簿
            from openpyxl import Workbook
            from openpyxl.styles import Font, Alignment
            
            wb = Workbook()
            
            # 1. 汇总统计表
            self.create_summary_sheet(wb)
            self.progress_bar.setValue(25)
            
            # 2. 详细数据表
            self.create_detail_sheet(wb)
            self.progress_bar.setValue(50)
            
            # 3. 用户统计表
            self.create_user_stats_sheet(wb)
            self.progress_bar.setValue(75)
            
            # 4. 统计报告表
            self.create_stats_report_sheet(wb)
            self.progress_bar.setValue(100)
            
            # 保存文件
            wb.save(path)
            self.progress_bar.setVisible(False)
            
            QMessageBox.information(self, "导出成功", f"综合报表已导出:\n{path}")
            
        except ImportError:
            self.progress_bar.setVisible(False)
            QMessageBox.warning(self, "导出失败", "需要安装 openpyxl 库才能导出Excel文件\n请执行: pip install openpyxl")
        except Exception as e:
            self.progress_bar.setVisible(False)
            log(f'[ERR] 导出Excel报表失败: {e}')
            QMessageBox.critical(self, "导出失败", f"导出报表失败:\n{e}")

    def create_summary_sheet(self, wb):
        """创建汇总统计表"""
        ws = wb.active
        ws.title = "汇总统计"
        
        # 标题
        ws['A1'] = "管理员汇总报表"
        ws['A1'].font = Font(bold=True, size=14)
        ws.merge_cells('A1:F1')
        
        ws['A2'] = f"统计日期: {self.date_edit.date().toString('yyyy-MM-dd')}"
        ws.merge_cells('A2:F2')
        
        # 汇总数据
        headers = ['统计项', '数值', '说明']
        data = [
            ['总用户数', len(self.user_stats), '参与工作的用户数量'],
            ['总记录数', sum(stats['total_records'] for stats in self.user_stats.values()), '总的工作记录条数'],
            ['总工作时长', self.format_duration(sum(stats['total_work_seconds'] for stats in self.user_stats.values())), '所有用户的总工作时间'],
            ['总工作量', sum(stats['total_workload'] for stats in self.user_stats.values()), '所有用户的工作量总和']
        ]
        
        for i, header in enumerate(headers, 1):
            ws.cell(row=4, column=i, value=header)
            ws.cell(row=4, column=i).font = Font(bold=True)
        
        for i, row_data in enumerate(data, 5):
            for j, value in enumerate(row_data, 1):
                ws.cell(row=i, column=j, value=value)

    def create_detail_sheet(self, wb):
        """创建详细数据表"""
        ws = wb.create_sheet("详细数据")
        headers = ['日期', '用户ID', '角色', '状态', '开始时间', '结束时间', '时长(秒)', '项目名称', '任务ID', '工作量1']
        
        for col, header in enumerate(headers, 1):
            ws.cell(row=1, column=col, value=header)
            ws.cell(row=1, column=col).font = Font(bold=True)
        
        if hasattr(self, 'all_data'):
            for row, record in enumerate(self.all_data, 2):
                print(f"这条记录的内容是：{record}")
                date_value = record.get('\ufeff日期', '') or record.get('日期', '')
                ws.cell(row=row, column=1, value=date_value.replace('-', '/'))
                ws.cell(row=row, column=2, value=record.get('用户ID', ''))
                ws.cell(row=row, column=3, value=record.get('角色', ''))
                ws.cell(row=row, column=4, value=record.get('状态', ''))
                ws.cell(row=row, column=5, value=record.get('开始', ''))
                ws.cell(row=row, column=6, value=record.get('结束', ''))
                ws.cell(row=row, column=7, value=record.get('时长(秒)', ''))
                ws.cell(row=row, column=8, value=record.get('项目名称', ''))
                ws.cell(row=row, column=9, value=record.get('任务ID', ''))
                ws.cell(row=row, column=10, value=record.get('工作量1', ''))

    def create_user_stats_sheet(self, wb):
        """创建用户统计表"""
        ws = wb.create_sheet("用户统计")
        headers = ['用户ID', '记录数', '总时长(秒)', '总工作量', '主要状态', '主要项目']
        
        for col, header in enumerate(headers, 1):
            ws.cell(row=1, column=col, value=header)
            ws.cell(row=1, column=col).font = Font(bold=True)
        
        if hasattr(self, 'user_stats'):
            for row, (user_id, stats) in enumerate(self.user_stats.items(), 2):
                main_state = max(stats['state_distribution'].items(), key=lambda x: x[1], default=('无', 0))[0]
                main_project = max(stats['project_distribution'].items(), key=lambda x: x[1], default=('无', 0))[0]
                
                ws.cell(row=row, column=1, value=user_id)
                ws.cell(row=row, column=2, value=stats['total_records'])
                ws.cell(row=row, column=3, value=stats['total_work_seconds'])
                ws.cell(row=row, column=4, value=stats['total_workload'])
                ws.cell(row=row, column=5, value=main_state)
                ws.cell(row=row, column=6, value=main_project)

    def create_stats_report_sheet(self, wb):
        """创建统计报告表"""
        ws = wb.create_sheet("统计报告")
        ws['A1'] = "数据统计报告"
        ws['A1'].font = Font(bold=True, size=12)

    def on_date_changed(self):
        """日期改变时重新加载数据"""
        self.load_data()

    def refresh_data(self):
        """刷新数据"""
        self.load_data()

    @staticmethod
    def format_duration(seconds):
        """格式化时长"""
        h, s = divmod(seconds, 3600)
        m, s = divmod(s, 60)
        return f"{h}小时{m}分{s}秒"


def show_admin_summary_window(data_dir):
    """外部唯一入口：返回管理员汇总窗口实例"""
    try:
        # 创建并显示窗口
        window = AdminSummaryWindow(data_dir)
        
        # 设置窗口标志
        window.setWindowFlags(Qt.WindowType.Window)
        window.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, True)
        window.setAttribute(Qt.WidgetAttribute.WA_QuitOnClose, False)
        
        window.show()
        window.raise_()
        window.activateWindow()
        
        return window
        
    except Exception as e:
        log(f'[ERR] 打开管理员汇总窗口失败: {e}')
        QMessageBox.critical(None, "错误", f"打开管理员汇总窗口失败:\n{e}")
        return None


if __name__ == "__main__":
    # 调试模式
    app = QApplication(sys.argv)
    window = AdminSummaryWindow("D:\\Tracker_Data")
    window.show()
    sys.exit(app.exec())